﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Rendering;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
using Newtonsoft.Json.Linq;

namespace NetCoreCMS.Web.Areas.Admin.Controllers.Order
{
    public class Order_ListController : ManageController
    {
        private const string WEB_VIEW = "~/Areas/Admin/Views/Order/order_list.cshtml";
        protected int totalCount;
        protected int page;
        protected int pageSize;

        protected int status;
        protected int payment_status;
        protected int express_status;
        protected string keywords = string.Empty;
        public IOrdersService _orders { get; set; }
        public IUsersService _users { get; set; }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (filterContext.Result != null)
                return;
            ChkAdminLevel("order_list", CMSEnums.ActionEnum.View.ToString()); //检查权限
            this.status = 0;
            int.TryParse(Request.Query["status"],out status);
            this.payment_status = 0;
            int.TryParse(Request.Query["payment_status"],out payment_status);
            this.express_status = 0;
            int.TryParse(Request.Query["express_status"],out express_status);
            this.keywords = Request.Query["keywords"];
            if (int.TryParse(Request.Query["pageNum"], out this.pageSize))
            {
                if (this.pageSize > 0)
                {
                    Response.Cookies.Append("order_list_page_size", this.pageSize.ToString());
                }
            }
            else
            {
                this.pageSize = GetPageSize(10); //每页数量
            }
            ViewBag.Status = this.status.ToString();
            ViewBag.PaymentStatus = this.payment_status.ToString();
            ViewBag.ExpressStatus = this.express_status.ToString();
            ViewBag.Keywords = this.keywords;
            ViewBag.PageNum = this.pageSize.ToString();
        }
        //
        // GET: /admin/Order_List/

        public ActionResult Index()
        {
            RptBind("where id>0" + CombSqlTxt(this.status, this.payment_status, this.express_status, this.keywords), "status asc,add_time desc,id desc");
            return View(WEB_VIEW);
        }

        public ActionResult SubmitDelete()
        {
            ChkAdminLevel("order_list", CMSEnums.ActionEnum.Delete.ToString()); //检查权限
            int sucCount = 0;
            int errorCount = 0;
            JObject jobject = JObject.Parse(Request.Form["json"]);
            JToken list = jobject["list"];
            foreach (JToken item in list)
            {
                int id = Convert.ToInt32(item["id"]);
                if (_orders.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(CMSEnums.ActionEnum.Delete.ToString(), "删除订单成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            string script = JscriptMsg("删除成功" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("index", "status={0}&payment_status={1}&express_status={2}&keywords={3}",
                this.status.ToString(), this.payment_status.ToString(), this.express_status.ToString(), this.keywords));
            return Content(script);
        }

        #region 数据绑定=================================
        private void RptBind(string _strWhere, string _orderby)
        {
            int.TryParse(Request.Query["page"], out this.page);
            this.page = this.page <= 0 ? 1 : this.page;
            ViewData["list"] = _orders.GetList(this.page, this.pageSize, _strWhere, _orderby, null);
            this.totalCount = _orders.RecordCount(_strWhere);
            string pageUrl = Utils.CombUrlTxt("index", "status={0}&payment_status={1}&express_status={2}&keywords={3}&page={4}",
                this.status.ToString(), this.payment_status.ToString(), this.express_status.ToString(), this.keywords, "__id__");
            ViewBag.PageContent = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);

            List<SelectListItem> statusList = new List<SelectListItem>(){
            new SelectListItem(){ Text="订单状态", Value="0" },
            new SelectListItem(){ Text="已生成", Value="1" },
            new SelectListItem(){ Text="已确认", Value="2" },
            new SelectListItem(){ Text="已完成", Value="3" },
            new SelectListItem(){ Text="已取消", Value="4" },
            new SelectListItem(){ Text="已作废", Value="5" }
         };
            ViewData["statusList"] = statusList;
            List<SelectListItem> payStatusList = new List<SelectListItem>() {
            new SelectListItem(){ Text="支付状态", Value="0" },
            new SelectListItem(){ Text="待支付", Value="1" },
            new SelectListItem(){ Text="已支付", Value="2" }
         };
            ViewData["paymentStatusList"] = payStatusList;
            List<SelectListItem> expressStatusList = new List<SelectListItem>() {
            new SelectListItem(){ Text="发货状态", Value="0" },
            new SelectListItem(){ Text="待发货", Value="1" },
            new SelectListItem(){ Text="已发货", Value="2" }
         };
            ViewData["expressStatusList"] = expressStatusList;
        }
        #endregion

        #region 组合SQL查询语句==========================
        protected string CombSqlTxt(int _status, int _payment_status, int _express_status, string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (_status > 0)
            {
                strTemp.Append(" and status=" + _status);
            }
            if (_payment_status > 0)
            {
                strTemp.Append(" and payment_status=" + _payment_status);
            }
            if (_express_status > 0)
            {
                strTemp.Append(" and express_status=" + _express_status);
            }            
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and (order_no like '%" + _keywords + "%' or user_name like '%" + _keywords + "%' or accept_name like '%" + _keywords + "%')");
            }
            return strTemp.ToString();
        }
        #endregion

        #region 返回用户每页数量=========================
        private int GetPageSize(int _default_size)
        {
            int _pagesize;
            if (int.TryParse(Request.Cookies["order_list_page_size"], out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion

        //导出

        public IActionResult SubmitExport()
        {
            ChkAdminLevel("order_list", CMSEnums.ActionEnum.Audit.ToString()); //检查权限
            return Export();
        }

        #region 封装后-导出、导入Excel.xlsx文件
        public IActionResult Export()
        {
            string dt1 = DateTime.Now.ToString("yyyy-MM-dd/HH:mm:ss.fff");
            string path = _env.WebRootPath;
            ExcelHelper.Export(GetDic(), path, out Tuple<string, string> t);
            string dt2 = DateTime.Now.ToString("yyyy-MM-dd/HH:mm:ss.fff");
            //return Json(new {
            //    msg = "ok",
            //    data = $"开始时间：{dt1},结束时间：{dt2}"
            //});

            return File(t.Item1, t.Item2);
        }

        private Dictionary<string, DataTable> GetDic()
        {
            DataTable dt = new DataTable("待发货订单");
            DataColumn dc1 = new DataColumn("序号", Type.GetType("System.String"));
            DataColumn dc2 = new DataColumn("用户名", Type.GetType("System.String"));
            DataColumn dc3 = new DataColumn("姓名", Type.GetType("System.String"));
            DataColumn dc4 = new DataColumn("电话", Type.GetType("System.String"));
            DataColumn dc5 = new DataColumn("地址", Type.GetType("System.String"));
            DataColumn dc6 = new DataColumn("订单号", Type.GetType("System.String"));
            DataColumn dc7 = new DataColumn("商品及数量", Type.GetType("System.String"));
            DataColumn dc8 = new DataColumn("总价", Type.GetType("System.String"));
            DataColumn dc9 = new DataColumn("日期", Type.GetType("System.String"));
            dt.Columns.Add(dc1);
            dt.Columns.Add(dc2);
            dt.Columns.Add(dc3);
            dt.Columns.Add(dc4);
            dt.Columns.Add(dc5);
            dt.Columns.Add(dc6);
            dt.Columns.Add(dc7);
            dt.Columns.Add(dc8);
            dt.Columns.Add(dc9);
            //以上代码完成了DataTable的构架，但是里面是没有任何数据的  
            var apply = _orders.GetList(1, 10000, "where payment_status=2 and express_status=1 and status<3", "id asc");
            for (int i = 0; i < apply.Count; i++)
            {
                try
                {
                    var user = _users.GetModel(apply[i].user_id);
                    if (user == null)
                        user = new NetCoreCMS.Models.Users { user_name = "删除" };
                    var om = _orders.GetModel(apply[i].id);
                    DataRow dr = dt.NewRow();
                    dr["序号"] = (i + 1).ToString();
                    dr["用户名"] = user.user_name;
                    dr["姓名"] = om.accept_name;
                    dr["电话"] = om.mobile;
                    dr["地址"] = om.area.Replace(",", "") + om.address;
                    dr["订单号"] = om.order_no;
                    string ss = "";
                    foreach (var item in om.order_goods)
                    {
                        ss += item.goods_title + "(" + item.quantity + "),";
                    }
                    dr["商品及数量"] = Utils.DelLastComma(ss);
                    dr["总价"] = om.order_amount.ToString();
                    dr["日期"] = om.add_time.ToString();
                    dt.Rows.Add(dr);
                }
                catch (Exception)
                {

                }
            }
            //填充了100000条相同的记录进去  

            var dic = new Dictionary<string, DataTable>();

            dic.Add($"{dt.TableName}", dt);

            return dic;
        }

        [HttpPost]
        public IActionResult Import(IFormFile excelFile)
        {
            string sWebRootFolder = _env.WebRootPath;
            try
            {
                ExcelHelper.Import(excelFile, sWebRootFolder, out string content);
                return Content(content);
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }
        #endregion
    }
}
